%% Global variables
%clear all
close all
clear global
clc
delete(gcp('nocreate'))
%delete(myCluster.Jobs)
distcomp.feature( 'LocalUseMpiexec', false )

%restoredefaultpath;
rehash toolboxcache;

%% Add paths
addpath('../Matlab')
addpath('../Matlab/matlab_bgl/')


%% Import network (adjacency matrix) and booleanized expression 
G = importdata(strcat('adjmat-DEbool-cutoff',cutoff,'.txt'));
InData = importdata(strcat('phenored-DEbool-cutoff',cutoff,'.txt'));


%% Formatting
RowName = G.textdata;
RowName(1) = [];
G = G.data;
BoolData = InData.data;
GNames = InData.textdata;
size(G)
size(BoolData)

% Sort/resize BoolData according to G
ind = zeros(size(RowName,1),1);
for i = 1:size(RowName,1)
    ind(i) = 1*find(strcmp(GNames, RowName(i)));    
end     
GNames = GNames(ind);
BoolData = BoolData(ind,:);


%% Find the shortest paths
[SP,P] = all_shortest_paths(sparse(abs(sign(G))),struct('algname','floyd_warshall')); 
%SP is the distance matrix, not used
%P is the predecessor matrix: Pij is the node preceding j in the shortest
%path from i to j: it is a node of the network

%% Indices of differentially expressed genes (all)
ind_data = (1:size(BoolData,1))';

%% Indices of variable/fixed edges
ind_optim = find(G);  % nonzero elements
ind_actinh = find(G==2); % 2 unspecified interation

%% Genetic algorithm
global iter;
iter = 1;
n_Population = 1500;  % Population size

% Iteration number file
global fName_iter_tmp;
delete('iteration.txt')
fName_iter_tmp = strcat('iteration.txt');
dlmwrite(fName_iter_tmp, iter);

delete(strcat('DEbool-cutoff',cutoff,'-2ph_GA_solutions.txt'));
fName_mismatch = strcat('DEbool-cutoff',cutoff,'-2ph_GA_solutions.txt');

MyPool = parpool;
display('GA started');
% Solver setup
optimproblem = struct;
optimproblem.fitnessfcn = @(P)myOptimFun_2attractor(P,BoolData(:,[1 2]),ind_optim,ind_actinh,ind_data,G,fName_mismatch,fName_iter_tmp);
optimproblem.nvars = numel(ind_optim)+numel(ind_actinh);
optimproblem.solver = 'ga';
optimproblem.options = gaoptimset('PlotFcns',{@gaplotbestf,@gaplotscorediversity},...
    'PopulationType','bitstring',...
    'UseParallel','always','PopulationSize',n_Population,'display','off','Generations', 100);

% Run generic algorithm
[P,fval,exitflag,output,Population,Scores] = ga(optimproblem);
display('GA finished');

delete(MyPool);

exit;